package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.BaseCategoryViewFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.search.dao.AlbumInfoDao;
import com.atguigu.tingshu.search.dao.SuggestIndexDao;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserClientFeign;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * es数据操作的实现类
 * es没有事务
 */
@Slf4j
@Service
public class ItemServiceImpl implements ItemService {

    private final AlbumInfoDao albumInfoDao;
    private final AlbumInfoFeignClient albumInfoFeignClient;
    private final UserClientFeign userClientFeign;
    private final BaseCategoryViewFeignClient baseCategoryViewFeignClient;
    private final SuggestIndexDao suggestIndexDao;
    private final RBloomFilter<Object> bloomFilter;

    @Autowired
    public ItemServiceImpl(AlbumInfoDao albumInfoDao, AlbumInfoFeignClient albumInfoFeignClient, UserClientFeign userClientFeign, BaseCategoryViewFeignClient baseCategoryViewFeignClient, SuggestIndexDao suggestIndexDao, RBloomFilter<Object> bloomFilter) {
        this.albumInfoDao = albumInfoDao;
        this.albumInfoFeignClient = albumInfoFeignClient;
        this.userClientFeign = userClientFeign;
        this.baseCategoryViewFeignClient = baseCategoryViewFeignClient;
        this.suggestIndexDao = suggestIndexDao;
        this.bloomFilter = bloomFilter;
    }

    /**
     * 上架
     *
     * @param albumId
     */
    @Override
    public void albumFromMysqlToEs(Long albumId) {
        // es的实体初始化
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        // 查询专辑的详细数据
        AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfoById(albumId);
        // albumInfo.getId() == null 后续解释
        if (albumInfo == null || albumInfo.getId() == null) {
            return;
        }
        albumInfoIndex.setId(albumId);
        // 专辑标题
        albumInfoIndex.setAlbumTitle(albumInfo.getAlbumTitle());
        // 专辑简介
        albumInfoIndex.setAlbumIntro(albumInfo.getAlbumIntro());
        // 专辑作者
        UserInfo userInfo = userClientFeign.getUserInfo(albumInfo.getUserId());
        String nickName = "默认名字";
        if (userInfo != null) {
            nickName = userInfo.getNickname();
        }
        albumInfoIndex.setAnnouncerName(nickName);
        // 专辑封面url
        albumInfoIndex.setCoverUrl(albumInfo.getCoverUrl());
        // 专辑声音总数
        albumInfoIndex.setIncludeTrackCount(albumInfo.getIncludeTrackCount());
        // 专辑是否完结
        albumInfoIndex.setIsFinished(albumInfo.getIsFinished().toString());
        // 专辑付费类型
        albumInfoIndex.setPayType(albumInfo.getPayType());
        // 专辑创建时间
        albumInfoIndex.setCreateTime(new Date());
        // 查询专辑的一级二级三级分类
        BaseCategoryView baseCategoryView = baseCategoryViewFeignClient.getBseCategoryView(albumInfo.getCategory3Id());
        albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
        albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        albumInfoIndex.setCategory3Id(baseCategoryView.getCategory3Id());
        // 查询专辑的统计数据
        Map<String, Object> albumStatMap = albumInfoFeignClient.getAlbumStat(albumId);
        // 播放量
        int playStatNum = Integer.parseInt(albumStatMap.get(SystemConstant.ALBUM_STAT_PLAY).toString());
        albumInfoIndex.setPlayStatNum(playStatNum);
        // 订阅量
        int subscribeStatNum = Integer.parseInt(albumStatMap.get(SystemConstant.ALBUM_STAT_SUBSCRIBE).toString());
        albumInfoIndex.setSubscribeStatNum(subscribeStatNum);
        // 购买量
        int buyStatNum = Integer.parseInt(albumStatMap.get(SystemConstant.ALBUM_STAT_BROWSE).toString());
        albumInfoIndex.setBuyStatNum(buyStatNum);
        // 评论数
        int commentStatNum = Integer.parseInt(albumStatMap.get(SystemConstant.ALBUM_STAT_COMMENT).toString());
        albumInfoIndex.setCommentStatNum(commentStatNum);
        // 权重计算专辑热度：playStatNum 1 / subscribeStatNum 2 / buyStatNum 5 / commentStatNum 3
        albumInfoIndex.setHotScore(new BigDecimal(playStatNum + 2 * subscribeStatNum + 5 * buyStatNum + 3 * commentStatNum).doubleValue());
        // 专辑属性值
        List<AlbumAttributeValue> albumAttributeValueList = albumInfoFeignClient.getAlbumAttributeValueList(albumId);
        // 转换为es的属性
        List<AttributeValueIndex> list = albumAttributeValueList.stream().map(albumAttributeValue -> {
            AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
            attributeValueIndex.setAttributeId(albumAttributeValue.getAttributeId());
            attributeValueIndex.setValueId(albumAttributeValue.getValueId());
            return attributeValueIndex;
        }).toList();
        albumInfoIndex.setAttributeValueIndexList(list);

        // 保存专辑到es
        albumInfoDao.save(albumInfoIndex);
        // 提示词的初始化
        suggestInit(albumInfoIndex);
        // 布隆过滤器添加
        bloomFilter.add(albumId);
    }

    /**
     * 提示词的初始化
     *
     * @param albumInfoIndex
     */
    private void suggestInit(AlbumInfoIndex albumInfoIndex) {
        // 专题的标题
        String albumTitle = albumInfoIndex.getAlbumTitle();
        saveSuggest(albumTitle, albumInfoIndex.getAlbumTitle());
        // 作者的名字
        saveSuggest(albumTitle, albumInfoIndex.getAnnouncerName());
        // 专辑的描述
        saveSuggest(albumTitle, albumInfoIndex.getAlbumIntro());
    }

    /**
     * 提示词初始化
     *
     * @param albumTitle
     * @param content
     */
    private void saveSuggest(String albumTitle, String content) {
        // 属性填充
        SuggestIndex suggestIndex = new SuggestIndex();
        suggestIndex.setId(UUID.randomUUID().toString().replace("-", ""));
        suggestIndex.setTitle(albumTitle);
        suggestIndex.setKeyword(new Completion(new String[]{content}));
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(content)}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(content)}));
        // 保存
        suggestIndexDao.save(suggestIndex);
    }

    /**
     * 下架
     *
     * @param albumId
     */
    @Override
    public void removeAlbumFromEs(Long albumId) {
        albumInfoDao.deleteById(albumId);
    }
}
